// ==UserScript==
// @name         Clipboard Manager with Confirmation and Selection
// @namespace    http://tampermonkey.net/
// @version      1.4
// @description  一个用于管理剪切板历史的侧边栏应用，带有可拖拽的呼出按钮，并支持跨域访问剪切板历史
// @author       You
// @match        *://*/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// ==/UserScript==

(function () {
    'use strict';

    // 默认按钮位置
    let buttonPosition = {top: 20, right: 10};

    // 获取存储的按钮位置
    async function loadButtonPosition() {
        const storedPosition = await GM_getValue('button_position', null);
        if (storedPosition) {
            buttonPosition = storedPosition;
        }
    }

    // 保存按钮位置
    async function saveButtonPosition(position) {
        await GM_setValue('button_position', position);
    }

    // 初始化剪切板历史记录
    let clipboardHistory = [];

    // 加载剪切板历史
    async function loadClipboardHistory() {
        clipboardHistory = await GM_getValue('clipboard_history', []);
    }

    // 保存剪切板历史
    async function saveClipboardHistory() {
        await GM_setValue('clipboard_history', clipboardHistory);
    }

    // 创建侧边栏
    const sidebar = document.createElement('div');
    sidebar.id = 'clipboard-sidebar';
    sidebar.style.position = 'fixed';
    sidebar.style.top = '0';
    sidebar.style.right = '-300px';
    sidebar.style.width = '300px';
    sidebar.style.height = '100%';
    sidebar.style.backgroundColor = '#f1f1f1';
    sidebar.style.borderLeft = '1px solid #ccc';
    sidebar.style.zIndex = '9999';
    sidebar.style.transition = 'right 0.3s ease';
    sidebar.style.overflowY = 'auto';
    sidebar.style.padding = '10px';
    sidebar.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.2)';
    document.body.appendChild(sidebar);

    // 创建侧边栏按钮
    const toggleButton = document.createElement('button');
    toggleButton.textContent = '📋 剪切板';
    toggleButton.style.position = 'fixed';
    toggleButton.style.top = `${buttonPosition.top}px`;
    toggleButton.style.right = `${buttonPosition.right}px`;
    toggleButton.style.zIndex = '10000';
    toggleButton.style.backgroundColor = '#4CAF50';
    toggleButton.style.color = 'white';
    toggleButton.style.padding = '10px';
    toggleButton.style.border = 'none';
    toggleButton.style.cursor = 'pointer';
    toggleButton.style.userSelect = 'none';  // 禁止文本选中
    document.body.appendChild(toggleButton);

    // 使按钮可拖拽，并限制它只能在右边界拖动
    function makeButtonDraggable(button) {
        let offsetY;

        button.onmousedown = function (e) {
            e.preventDefault();
            offsetY = e.clientY - button.getBoundingClientRect().top;

            document.onmousemove = function (e) {
                e.preventDefault();
                // 限制按钮只能在屏幕右侧拖动
                const newTop = e.clientY - offsetY;
                const maxTop = window.innerHeight - button.offsetHeight;
                button.style.top = `${Math.min(Math.max(newTop, 0), maxTop)}px`;
            };

            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
                // 保存按钮位置
                saveButtonPosition({top: parseInt(button.style.top), right: 10});
            };
        };
    }

    makeButtonDraggable(toggleButton);

    // 创建历史记录列表容器
    const historyList = document.createElement('ul');
    historyList.style.listStyle = 'none';
    historyList.style.padding = '0';
    sidebar.appendChild(historyList);

    // 创建手动添加记录的功能
    const addRecordForm = document.createElement('form');
    const input = document.createElement('input');
    input.type = 'text';
    input.placeholder = '新建记录...';
    input.style.width = 'calc(100% - 20px)';
    input.style.marginBottom = '10px';
    input.style.padding = '5px';
    const addButton = document.createElement('button');
    addButton.textContent = '添加';
    addButton.style.display = 'block';
    addButton.style.width = '100%';
    addButton.style.padding = '5px';
    addButton.style.backgroundColor = '#4CAF50';
    addButton.style.color = 'white';
    addButton.style.border = 'none';
    addButton.style.cursor = 'pointer';
    addRecordForm.appendChild(input);
    addRecordForm.appendChild(addButton);
    sidebar.insertBefore(addRecordForm, historyList);

    // 创建全选删除按钮
    const deleteAllButton = document.createElement('button');
    deleteAllButton.textContent = '全选删除';
    deleteAllButton.style.width = '100%';
    deleteAllButton.style.padding = '5px';
    deleteAllButton.style.backgroundColor = '#f44336';
    deleteAllButton.style.color = 'white';
    deleteAllButton.style.border = 'none';
    deleteAllButton.style.cursor = 'pointer';
    deleteAllButton.style.marginBottom = '10px';
    sidebar.insertBefore(deleteAllButton, historyList);

    // 更新剪切板历史 UI
    function updateHistoryUI() {
        historyList.innerHTML = '';

        clipboardHistory.forEach((item, index) => {
            const listItem = document.createElement('li');
            listItem.style.padding = '5px';
            listItem.style.borderBottom = '1px solid #ccc';
            listItem.style.display = 'flex';
            listItem.style.justifyContent = 'space-between';
            listItem.style.alignItems = 'center';

            // 显示文本内容
            const textNode = document.createElement('span');
            textNode.textContent = item;
            listItem.appendChild(textNode);

            // 创建复制按钮
            const copyButton = document.createElement('button');
            copyButton.textContent = '复制';
            copyButton.style.marginLeft = '10px';
            copyButton.style.backgroundColor = '#2196F3';
            copyButton.style.color = 'white';
            copyButton.style.border = 'none';
            copyButton.style.cursor = 'pointer';
            copyButton.addEventListener('click', () => {
                navigator.clipboard.writeText(item); // 不需要确认
            });
            listItem.appendChild(copyButton);

            // 创建删除按钮
            const deleteButton = document.createElement('button');
            deleteButton.textContent = '删除';
            deleteButton.style.marginLeft = '10px';
            deleteButton.style.backgroundColor = '#f44336';
            deleteButton.style.color = 'white';
            deleteButton.style.border = 'none';
            deleteButton.style.cursor = 'pointer';
            deleteButton.addEventListener('click', (e) => {
                e.stopPropagation();
                if (confirm('确定要删除这条记录吗？')) {
                    removeHistoryItem(index);
                }
            });
            listItem.appendChild(deleteButton);

            historyList.appendChild(listItem);
        });
    }

    // 添加新记录到剪切板历史
    function addHistoryItem(item) {
        clipboardHistory.push(item);
        saveClipboardHistory();
        updateHistoryUI();
    }

    // 删除剪切板历史中的特定项
    function removeHistoryItem(index) {
        clipboardHistory.splice(index, 1);
        saveClipboardHistory();
        updateHistoryUI();
    }

    // 全选删除功能
    deleteAllButton.addEventListener('click', () => {
        if (confirm('确定要删除所有记录吗？')) {
            clipboardHistory = []; // 清空历史记录
            saveClipboardHistory();
            updateHistoryUI();
        }
    });

    // 切换侧边栏显示/隐藏
    toggleButton.addEventListener('click', () => {
        sidebar.style.right = sidebar.style.right === '0px' ? '-300px' : '0px';
    });

    // 添加记录表单提交事件
    addRecordForm.addEventListener('submit', (e) => {
        e.preventDefault();
        const newItem = input.value.trim();
        if (newItem) {
            addHistoryItem(newItem);
            input.value = '';
        }
    });

    // 初始加载剪切板历史和按钮位置
    loadClipboardHistory().then(updateHistoryUI);
    loadButtonPosition().then(() => {
        toggleButton.style.top = `${buttonPosition.top}px`;
        toggleButton.style.right = `${buttonPosition.right}px`;
    });
})();
